package com.xingzhe.pengji.security.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.xingzhe.pengji.security.dao.UserIbatisDao;
import com.xingzhe.pengji.security.domain.User;
import com.xingzhe.pengji.security.services.UserService;

/**
 * @Title ： 三江学院 毕业设计
 * @Description ：
 * @author ：LuFengLiang
 * @Company: IT行者工作室
 * @Copyright: Copyright (c) 2012-2-24
 * @version ： 1.0
 * @param <T>
 */
@Service("userService")
public class UserServiceImpl<T extends User> implements UserService<T>
{
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserIbatisDao<T> userIbatisDao;
    
    @Override
    public List<T> queryForPageUserList(T entity, String sortByColumn, int pageSize, int pageNumber, boolean sortAsc)
    {
        return userIbatisDao.queryForPaginatedList(organizeParams(entity), pageNumber, pageSize, sortByColumn, sortAsc);
    }
    
    @Override
    public void saveUser(T entity)
    {
        boolean b = userIbatisDao.addUser(entity);
        if ( !b )
        {
            logger.error("新增用户失败");
        }
    }
    
    @Override
    public void updateUser(T entity)
    {
        boolean b = userIbatisDao.updateUser(entity);
        if ( !b )
        {
            logger.error("更新用户失败！");
        }
    }
    
    @Override
    public void delUser(T entity)
    {
        entity.setDelFlag(-1);
        boolean b = userIbatisDao.updateUser(entity);
        if ( !b )
        {
            logger.error("删除用户失败！");
        }
    }
    
    @Override
    public T getUserByAccount(T entity)
    {
        
        if ( userIbatisDao.getUsers(organizeParams(entity)).size() != 0 )
        {
            T user = userIbatisDao.getUsers(organizeParams(entity)).get(0);
            if ( null != user )
            {
                return user;
            }
            else
            {
                return user;
            }
        }
        return null;
    }
    
    @Override
    public T getUserById(T entity)
    {
        if ( userIbatisDao.getUsers(organizeParams(entity)).size() != 0 )
        {
            T user = userIbatisDao.getUsers(organizeParams(entity)).get(0);
            if ( null != user )
            {
                return user;
            }
            else
            {
                return null;
            }
        }
        return null;
    }
    
    @Override
    public int getItemCount(T entity)
    {
        return userIbatisDao.getItemCount(organizeParams(entity));
    }
    
    @SuppressWarnings("unchecked")
    private Map<String, Object> organizeParams(T entity)
    {
        if ( null == entity )
        {
            entity = (T) new User();
        }
        if ( null != entity.getAccount() && ("".equals(entity.getAccount().trim())) )
        {
            entity.setAccount(null);
        }
        // 用于存放参数值的容器，用于Ibatis条件查询是取值
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", entity.getId());
        params.put("name", entity.getName());
        params.put("email", entity.getEmail());
        params.put("account", entity.getAccount());
        
        params.put("isSys", entity.getIsSys());
        params.put("enabled", entity.getEnabled());
        params.put("accountNonLocked", entity.getAccountNonLocked());
        params.put("accountNonExpired", entity.getAccountNonExpired());
        params.put("credentialsNonExpired", entity.getCredentialsNonExpired());
        
        return params;
    }
    
    /**
     * 判断邮箱是否存在
     */
    @Override
    public T judgeEmialExit(T entity)
    {
        if ( userIbatisDao.getUsers(organizeParams(entity)).size() != 0 )
        {
            T user = userIbatisDao.getUsers(organizeParams(entity)).get(0);
            if ( null != user )
            {
                return user;
            }
            else
            {
                return null;
            }
        }
        return null;
    }
    
    
    @Override
	public List<GrantedAuthority> loadUserAuthoritiesByName(String userName) {
		try {
			List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			List<String> authoritieNames = userIbatisDao.getAllAuthoritiesByUserName(userName);
			for (String authoritieName : authoritieNames) {
				SimpleGrantedAuthority a = new SimpleGrantedAuthority(authoritieName);
				//SwitchUserGrantedAuthority a = new SwitchUserGrantedAuthority(authoritieName,null);
				auths.add(a);
			}
			return auths;
		} catch (RuntimeException e) {
			//log.error("find by authorities by username failed.", e);
			throw e;
		}
	}

	@Override
	public T getUserByAccount(String account) {
		T u=(T) new User();
		u.setAccount(account);
		return getUserByAccount(u);
	}
    
}
